import 'dart:async';
import 'dart:io';

import 'package:dio/adapter.dart';
import 'package:flutter/material.dart';
import 'package:barcode_scan/barcode_scan.dart';
import 'package:dio/dio.dart';
import 'package:shared_preferences/shared_preferences.dart';
import 'Util.dart';

class ResultPage extends StatefulWidget {
  ResultPage({Key key, this.title,this.para}) : super(key: key);
  final String title;
  final Map<String,dynamic> para;
  @override
  _ResultPage createState() => _ResultPage();
}

class _ResultPage extends State<ResultPage> {
  Timer timer;
  int seconds = -1;
  @override
  void initState() {
    // TODO: implement initState
    super.initState();
    loadData();
  }
  void loadData() {
    SharedPreferences.getInstance().then((value){
      setState(() {
        String domain = value.getString("buildings").toMap()["subdomain"].toString();
        print(domain);
        var dic = widget.para;
        dic["api_key"] = "xQITe6bZFUrmeJbkcKgkUzajUI6FGLA";
        dic["lang"] = "en";
        print(dic);
        var dio = Dio();
        if (ShareHandle.instance.proxy.length > 0){
          (dio.httpClientAdapter as DefaultHttpClientAdapter).onHttpClientCreate = (HttpClient client){
            client.findProxy = (uri) {
              return ShareHandle.instance.proxy;
            };
          };
        }
        var defaultApi = "/visitor/register";
        if (dic["visitor_key"].toString().isNotEmpty){
          defaultApi = "/visitor/scan_register";
        }
        dio.post("${domain}/api${defaultApi}",data:FormData.fromMap(dic)).then((response){
          final result = response.toResult();
          if (result.item2){
            setState(() {
              this.seconds = 10;
              this.text = "身份已確認~謝謝!${seconds >= 0 ? "\n(${this.seconds}秒)" : ""}";
              this.img = "assets/images/icon_key_passed.png";
            });
            this.timer = Timer.periodic(Duration(seconds: 1), (timer) {
              seconds -= 1;
              setState(() {
                this.text = "身份已確認~謝謝!${seconds >= 0 ? "\n(${this.seconds}秒)" : ""}";
              });
              if (seconds < 0){
                this.timer.cancel();
                Navigator.of(context).popUntil((route) => route.settings.name == "MyHome2Page");
              }
            });
          }else{
            showAlert(result.item4);
          }
        }).catchError((error){
          print("error:${error}");
          showAlert(error);
        });
      });
    });
  }
  String text = "身份確認中，請耐心等待~謝謝!";
  String img = "assets/images/icon_key_checking.png";
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text(widget.title),
      ),
      body: Center(
        child: Column(children: <Widget>[
          Image(image: AssetImage(this.img),),
          Text(text,textAlign: TextAlign.center,)
        ],),
      ),
    );
  }
}
